package com.wyg.study.annotation.log;

import com.alibaba.fastjson.JSON;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author yg.wang
 * @description:
 * @date 2019/7/25 16:27
 */
@Aspect
@Component
public class LogAspect {
    private static final Logger logger = LoggerFactory.getLogger(LogAspect.class);

    @Pointcut("@annotation(com.wyg.study.annotation.log.Log)")
    private void log() {

    }

    @Around("log()")
    public Object printLog(ProceedingJoinPoint joinPoint) throws Throwable {
        String className = joinPoint.getTarget().getClass().getName();

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        logger.info("method\t-->\t" + className + "." + method.getName());
        Object[] args = joinPoint.getArgs();
        logger.info("params\t-->\t" + JSON.toJSONString(args));
        Object proceed = joinPoint.proceed();
        logger.info("return\t-->\t" + JSON.toJSONString(proceed));
        return proceed;
    }

    @AfterThrowing(throwing = "e", pointcut = "log()")
    public void handleEx(JoinPoint joinPoint, Throwable e) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Log annotation = signature.getMethod().getAnnotation(Log.class);
        if (annotation.exceptionIncluded()) {
            logger.info("exception\t-->\t", e);
        }
    }
}
